package com.cloudkinto.service.company.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.Base64AndFileStreamUtil;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.OkHttpUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.StockRecordPageDto;
import com.cloudkinto.service.company.CompanyAuthorizeService;
import com.cloudkinto.service.company.vo.*;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.order.TemuOrderBackProductService;
import com.cloudkinto.service.order.TemuOrderBackService;
import com.cloudkinto.service.orderoutput.OrderOutputPackageDetailService;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.OrderOutputTemuProductService;
import com.cloudkinto.service.orderoutput.openapivo.OpenApiOrderOutputAddReq;
import com.cloudkinto.service.orderoutput.openapivo.OpenApiOrderOutputProductAddReq;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.product.vo.ProductPageRes;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.stock.vo.log.StockLogPageRes;
import com.cloudkinto.utils.TemuUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2024-09-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
@RequiredArgsConstructor
public class CompanyAuthorizeServiceImpl extends ServiceImpl<CompanyAuthorizeDao, CompanyAuthorizeDo> implements CompanyAuthorizeService {
    private final CompanyAuthorizeDao dao;
    private final CompanyDao companyDao;
    private final ProductInfoService productInfoService;
    private final StockRecordDao stockRecordDao;
    private final StorageDao storageDao;
    private final StockLogService stockLogService;
    private final OrderOutputService orderOutputService;
    private final OrderOutputTemuProductService orderOutputTemuProductService;
    private final FileService fileService;
    private final ShipPriceService shipPriceService;
    private final DimensDao dimensDao;
    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private final TemuOrderBackService temuOrderBackService;
    private final TemuOrderBackProductService temuOrderBackProductService;
    private final DicBusinessItemDao dicBusinessItemDao;
    private final OrderOutputPackageDetailService packageDetailService;
    private final OrderOutputTemuProductDao orderOutputTemuProductDao;

    @Override
    public SingleResult pageInit(Long companyId) {
        Map<String, Object> result = new HashMap<>();
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>().eq(CompanyAuthorizeDo::getCompanyId, companyId).eq(CompanyAuthorizeDo::getType, "temu").orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null) {
            result.put("active", 0);
        } else {
            result.put("active", et.getActive());
            result.put("authKey", et.getAuthKey());
            result.put("token", et.getToken());
        }
        return SingleResult.success(result);
    }


    @Override
    public String generateCustomAuthKey(CompanyAuthUpdateReq req, Long companyId, Long userId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                .eq(CompanyAuthorizeDo::getCompanyId, companyId)
                .eq(CompanyAuthorizeDo::getShopId, req.getShopId())
                .eq(CompanyAuthorizeDo::getType, "temu")
                .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null && (req.getOperateType() == 1 || req.getOperateType() == 2)) {
            return "";
        }

        if (req.getOperateType() == 1) {
            if (et.getActive() == 1) {
                return "";
            }
            //启用
            et.setActive(1);
        } else if (req.getOperateType() == 2) {
            if (et.getActive() == 0) {
                return "";
            }
            //禁用
            et.setActive(0);
        } else if (req.getOperateType() == 3) {

            String token = UUID.randomUUID().toString();
            String authKey = "";
            if (et == null) {
                et = new CompanyAuthorizeDo();
                CompanyDo companyDo = companyDao.selectById(companyId);
                if (companyDo == null) {
                    throw new BizException(SysConstant.No_Company_Info);
                }
                authKey = companyDo.getCompanyCode() + "_" + req.getShopId() + UUID.randomUUID().toString().substring(23);
                et.setCompanyCode(companyDo.getCompanyCode() + req.getShopId());
                et.setShopId(req.getShopId());
                et.setCompanyId(companyId);
                et.setType("temu");

            } else {
                authKey = et.getCompanyCode() + "_" + req.getShopId() + UUID.randomUUID().toString().substring(23);

            }
            et.setToken(authKey);
            et.setAuthKey(authKey);
            et.setActive(1);

        } else {
            return "";
        }
        if (et.getId() != null) {
            // et.setUpdateBy(userId);
            et.setUpdateTime(new Date());
            dao.updateById(et);
        } else {
            // et.setCreateBy(userId);
            et.setCreateTime(new Date());
            dao.insert(et);
        }
        return et.getAuthKey();
    }


    /**********************************************************TEMU平台授权************************************************************************************/

    /**
     * 我们掉 temu 接口，成功后 跳转 redirectLink 返回temy授权页面，需要带着ticket
     * 商家跳转服务商网站，取出 ticket 的值后，调用(bg.certified.warehouse.token.info.push)接口把 ticket、货主 code、授权 key、授权 token 推送到 Temu，详情见文档附录 8
     *
     * @param req
     * @param companyId
     * @param userId
     * @return
     */
    @Override
    public SingleResult temuTokenInfoPush(TemuAuthorizeReq req, Long companyId, Long userId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                .eq(CompanyAuthorizeDo::getShopId, req.getShopId())
                .eq(CompanyAuthorizeDo::getCompanyId, companyId)
                .eq(CompanyAuthorizeDo::getActive, 1)
                .eq(CompanyAuthorizeDo::getType, "temu")
                .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null) {
            this.generateCustomAuthKey(new CompanyAuthUpdateReq(3), companyId, null);
            et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                    .eq(CompanyAuthorizeDo::getCompanyId, companyId)
                    .eq(CompanyAuthorizeDo::getShopId, req.getShopId())
                    .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        }
        if (et == null || et.getActive() == 0) {
            throw new BizException(SysConstant.TemuAuth_Not_EXIST_Error);
        }
        //存在密钥 掉temu授权接口 bg.certified.warehouse.token.info.push

        // Map<String, Object> paramMap = new HashMap<>();
        // paramMap.put("ticket", req.getTicket());
        // paramMap.put("cwProviderCode", "JDY");
        // paramMap.put("cwProviderName", "筋斗云");
        // paramMap.put("cwCustomCode", et.getCompanyCode());
        // paramMap.put("cwAppKey", et.getAuthKey());
        // paramMap.put("cwAccessToken", et.getToken());
//        String sign = TemuUtils.signRequest(JSON.toJSONString(paramMap), et.getToken());
//        paramMap.put("sign", sign);
        String result = null;
        req.setCompanyId(companyId);
        try {
            result = OkHttpUtils.okHttpRequest("https://cloudkinto.co.jp/api/CompanyAuthorize/temuTokenInfoPush1", "POST", JSONObject.toJSONString(req));
            // result = TemuUtils.doPost("bg.certified.warehouse.token.info.push", et.getToken(), paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(result)) {
            return SingleResult.failure("500", "连接超时");
        }
        TemuApiRes res = JSON.parseObject(result, TemuApiRes.class);
        if (res.getSuccess() != null && res.getSuccess()) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(res.getErrorCode() + ": " + res.getErrorMsg());
        }
    }

    @Override
    public String temuTokenInfoPush1(String ticket, Long shopId, Long companyId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                .eq(CompanyAuthorizeDo::getShopId, shopId)
                .eq(CompanyAuthorizeDo::getCompanyId, companyId)
                .eq(CompanyAuthorizeDo::getType, "temu")
                .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null) {
            this.generateCustomAuthKey(new CompanyAuthUpdateReq(3), companyId, null);
            et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                    .eq(CompanyAuthorizeDo::getCompanyId, companyId)
                    .eq(CompanyAuthorizeDo::getShopId, shopId)
                    .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        }
        if (et == null || et.getActive() == 0) {
            throw new BizException(SysConstant.TemuAuth_Not_EXIST_Error);
        }

        //存在密钥 掉temu授权接口 bg.certified.warehouse.token.info.push

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("ticket", ticket);
        paramMap.put("cwProviderCode", "JDY");
        paramMap.put("cwProviderName", "筋斗云");
        paramMap.put("cwCustomCode", et.getCompanyCode());
        paramMap.put("cwAppKey", et.getAuthKey());
        paramMap.put("cwAccessToken", et.getToken());
//        String sign = TemuUtils.signRequest(JSON.toJSONString(paramMap), et.getToken());
//        paramMap.put("sign", sign);
        String result = null;
        try {
            result = TemuUtils.doPost("bg.certified.warehouse.token.info.push", et.getToken(), paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(result)) {
            //     return SingleResult.failure("500", "连接超时");
            // }
            // TemuApiRes res = JSON.parseObject(result, TemuApiRes.class);
            // if (res.getSuccess() != null && res.getSuccess()) {
            //     return SingleResult.success();
            // } else {
            //     return SingleResult.failure(res.getErrorCode() + ": " + res.getErrorMsg());
            // }
        }
        return result;
    }

    @Override
    public TemuAuthVerifyResponse tokenVerifyApi(TemuAuthTokenVerifyReq req) {
        TemuAuthVerifyRes res = this.tokenVerify(req);
        TemuAuthVerifyResponse response = new TemuAuthVerifyResponse();
        BeanUtils.copyProperties(res, response);
        return response;
    }


    /**
     * 商家绑定对接仓仓库货主 code 和 token 后，调用(bg.certified.warehouse.token.verify)向对接仓验证 token 的有效性
     *
     * @param req
     * @return
     */
    @Override
    public TemuAuthVerifyRes tokenVerify(TemuAuthTokenVerifyReq req) {
        TemuAuthVerifyRes response = new TemuAuthVerifyRes();
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                .eq(CompanyAuthorizeDo::getCompanyCode, req.getCwCustomCode())
                .eq(CompanyAuthorizeDo::getType, "temu")
                .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null) {
            response.setErrorCode(100000);
            response.setErrorMsg("对接仓仓库的货主 code 未匹配");
            return response;
        }
        // if (!Objects.equals(et.getAuthKey(), req.getCwAppKey())) {
        //     response.setErrorCode(200000);
        //     response.setErrorMsg("合作仓仓库的授权 key 不正确");
        //     return response;
        // }
        if (!Objects.equals(et.getToken(), req.getCwAccessToken())) {
            response.setErrorCode(300000);
            response.setErrorMsg("合作仓仓库的授权 token 不正确");
            return response;
        }
        if (et.getActive() == 0) {
            response.setErrorCode(400000);
            response.setErrorMsg("合作仓仓库的授权 token 已禁用");
        }
        response.setSuccess(true);
        response.setResult(new TemuAuthVerifyApiRes.Result(true));
        response.setEt(et);
        return response;
    }


    /**
     * temu 掉我们接口 获取skuInfo信息
     *
     * @param req
     * @return
     */
    @Override
    public ProductQueryResponse getSkuInfoList(ProductQueryReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new ProductQueryResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
        CompanyAuthorizeDo et = checkRes.getEt();
        Map<String, String> map = new HashMap<>();
        map.put("companyId", et.getCompanyId() + "");
        map.put("current", req.getPageNo() + "");
        map.put("pageSize", req.getPageSize() + "");
        if (req.getCwSkuCodeList() != null && !req.getCwSkuCodeList().isEmpty()) {
            map.put("cwSkuCodeList", StringUtils.join(req.getCwSkuCodeList(), ","));
        }
        PageResult<ProductPageRes> pageResult = productInfoService.getListPage(map);


        List<SkuInfo> skuInfoList = new ArrayList<>(pageResult.getValues().size());
        for (ProductPageRes value : pageResult.getValues()) {
            skuInfoList.add(new SkuInfo(value.getCommoditySku(), value.getProductName(), value.getProductName(),
                    String.valueOf(value.getLength()), String.valueOf(value.getWidth()), String.valueOf(value.getHeight()), String.valueOf(value.getWeight())));
        }

        ProductQueryResponse response = new ProductQueryResponse();
        response.setSuccess(true);
        response.setResult(new ProductQueryResponse.Result(Long.parseLong(pageResult.getPageInfo().getTotal() + ""), skuInfoList));
        return response;

    }

    @Override
    public TemuBaseQueryRes<ProductQueryDetailResponse> getSkuInfoDetail(ProductQueryReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new TemuBaseQueryRes(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
        CompanyAuthorizeDo et = checkRes.getEt();
        Map<String, String> map = new HashMap<>();
        map.put("companyId", et.getCompanyId() + "");
        map.put("current", req.getPageNo() + "");
        map.put("pageSize", req.getPageSize() + "");
        if (req.getCwSkuCodeList() != null && !req.getCwSkuCodeList().isEmpty()) {
            map.put("cwSkuCodeList", StringUtils.join(req.getCwSkuCodeList(), ","));
        }
        PageResult<ProductPageRes> pageResult = productInfoService.getListPage(map);


        List<ProductQueryDetailResponse.SkuInfoListDTO> skuInfoList = new ArrayList<>(pageResult.getValues().size());
        for (ProductPageRes value : pageResult.getValues()) {
            //todo
            ProductQueryDetailResponse.SkuInfoListDTO skuDetail = new ProductQueryDetailResponse.SkuInfoListDTO();
            skuDetail.setCwSkuCode(value.getCommoditySku());
            skuDetail.setName(value.getProductName());
            skuDetail.setEnName(value.getCommodityName());
            skuDetail.setCategories(new ProductQueryDetailResponse.SkuInfoListDTO.CategoriesDTO(value.getProductType(), "-", "-"));
            skuDetail.setPropertyList(new ArrayList<>());
            List<ProductQueryDetailResponse.SkuInfoListDTO.BarCodeListDTO> barcodeList = new ArrayList<>();
            if (value.getUpc() != null)
                barcodeList.add(new ProductQueryDetailResponse.SkuInfoListDTO.BarCodeListDTO(value.getUpc(), 2));
            if (value.getFnSku() != null)
                barcodeList.add(new ProductQueryDetailResponse.SkuInfoListDTO.BarCodeListDTO(value.getFnSku(), 2));
            skuDetail.setBarCodeList(barcodeList);
            skuDetail.setOuterPackage(new ProductQueryDetailResponse.SkuInfoListDTO.OuterPackageDTO());
            skuDetail.setSpecProperty(new ProductQueryDetailResponse.SkuInfoListDTO.SpecPropertyDTO(String.valueOf(value.getLength()),
                    String.valueOf(value.getWidth()), String.valueOf(value.getHeight()), String.valueOf(value.getWeight() * 1000), String.valueOf(value.getColor())));
            skuDetail.setSalesLinkList(new ArrayList<>());
            skuDetail.setImageUrl(value.getProductPictureFileUrl());
            skuInfoList.add(skuDetail);
        }

        TemuBaseQueryRes response = new TemuBaseQueryRes();
        response.setSuccess(true);
        response.setResult(new ProductQueryDetailResponse(Long.parseLong(pageResult.getPageInfo().getTotal() + ""), skuInfoList));
        return response;
    }

    /**
     * 修改商品信息 我们 需要调取temu接口
     * 对接仓商品信息发生变更，通过（bg.certified.warehouse.sku.change.info.push）接口推送给 temu
     *
     * @param req
     * @param companyId
     * @return
     */
    @Override
    public SingleResult skuInfoChangeInfoPush(SkuInfoChangeReq req, Long companyId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>().eq(CompanyAuthorizeDo::getCompanyId, companyId).orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null || et.getActive() == 0) {
            return SingleResult.failure(SysConstant.TemuAuth_Not_EXIST_Error);
//            throw new BizException(SysConstant.TemuAuth_Not_EXIST_Error);
        }
        //存在密钥 掉temu授权接口 bg.certified.warehouse.token.info.push

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("cwProviderCode", "JDY");
        paramMap.put("cwProviderName", "筋斗云");
        paramMap.put("cwSkuCode", req.getCwSkuCode());
        paramMap.put("cwCustomCode", et.getCompanyCode());
        paramMap.put("cnName", req.getCnName());
        paramMap.put("name", req.getName());
        paramMap.put("length", req.getLength());
        paramMap.put("width", req.getWidth());
        paramMap.put("height", req.getHeight());
        paramMap.put("weight", req.getWeight());
        String result = null;
        try {
            result = TemuUtils.doPost("bg.certified.warehouse.sku.info.change.push", et.getToken(), paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(result)) {
            return SingleResult.failure("500", "连接超时");
        }
        SkuInfoChangePushResponse res = JSON.parseObject(result, SkuInfoChangePushResponse.class);
        if (res.getSuccess() != null && res.getSuccess()) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(res.getErrorCode() + ": " + res.getErrorMsg());
        }
    }


    /**
     * 库存查询接口
     *
     * @param req
     * @return
     */
    @Override
    public InventoryQueryResponse getInventoryList(InventoryQueryReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new InventoryQueryResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
        CompanyAuthorizeDo et = checkRes.getEt();
        Map<String, String> map = new HashMap<>();
        map.put("companyId", et.getCompanyId() + "");
        if (et.getShopId() != null) {
            map.put("shopId", et.getShopId() + "");
        }
        if (req.getCwSkuCodeList() != null && !req.getCwSkuCodeList().isEmpty()) {
            map.put("cwSkuCodeList", StringUtils.join(req.getCwSkuCodeList(), ","));
        }
        List<StockRecordPageDto> stockList = stockRecordDao.listPage(map);
        Map<String, List<StockRecordPageDto>> collect = stockList.stream().collect(Collectors.groupingBy(StockRecordPageDto::getCommoditySku));

        Map<String, List<InventoryInfo>> inventoryInfoMap = new HashMap<>();

        for (String sku : collect.keySet()) {
            List<InventoryInfo> infoList = new ArrayList<>();
            for (StockRecordPageDto pageDto : collect.get(sku)) {
                //可用库存 = 在库 - 一件代发未发 - fba未发
                InventoryInfo info = new InventoryInfo(pageDto.getCommoditySku(), pageDto.getStorageName(), pageDto.getStorageName(),
                        pageDto.getCanSellCount() + pageDto.getFreezeCount(), pageDto.getInTransit(), pageDto.getCanSellCount() - pageDto.getNoDelivered() - pageDto.getTurnFba());
                infoList.add(info);
            }
            inventoryInfoMap.put(sku, infoList);
        }

        InventoryQueryResponse response = new InventoryQueryResponse();
        response.setSuccess(true);
        response.setResult(new InventoryQueryResponse.Result(inventoryInfoMap));
        return response;
    }


    /**
     * 库存流水查询接口
     */
    @Override
    public InventoryChangeListResponse inventoryChangeListGet(InventoryChangeListReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new InventoryChangeListResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
        InventoryChangeListResponse response = new InventoryChangeListResponse();
        CompanyAuthorizeDo et = checkRes.getEt();
        StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, req.getCwWarehouseCode()).last(" order by id desc limit 1"));
        if (storageDo == null) {
            response.setErrorCode(500000);
            response.setErrorMsg("对接仓仓库编码 未匹配");
            return response;
        }


        Map<String, String> map = new HashMap<>();
        map.put("companyId", et.getCompanyId() + "");
        map.put("shopId", et.getShopId() + "");
        map.put("storageId", storageDo.getId() + "");
        map.put("sku", req.getCwSkuCode());
        map.put("status", "0");//良品
        long start = req.getStartTime() * 1000L;
        long end = req.getEndTime() * 1000L;
        map.put("startDate", DateUtils.dateFormatToString(new Date(start), "yyyy-MM-dd HH:mm:ss"));
        map.put("endDate", DateUtils.dateFormatToString(new Date(end), "yyyy-MM-dd HH:mm:ss"));
        map.put("current", req.getPageNo() + "");
        map.put("pageSize", req.getPageSize() + "");

        PageResult<StockLogPageRes> listPage = stockLogService.getListPage(map);
        List<InventoryChange> inventoryChangeList = new ArrayList<>();
        for (StockLogPageRes value : listPage.getValues()) {
            InventoryChange change = new InventoryChange();
            change.setUniqueId(value.getId() + "");
            change.setCwSkuCode(value.getCommoditySku());
            change.setCwWarehouseCode(value.getStorage());
            change.setPlatformOpt(true);
            if (StaticDict.STOCK_ADJUST_TYPE.ORDER_OUT.getValue().equals(value.getNoteType()) || StaticDict.STOCK_ADJUST_TYPE.FBA_OUT.getValue().equals(value.getNoteType())) {
                //一件代发出库
                change.setOptType("130");
            } else if (StaticDict.STOCK_ADJUST_TYPE.ORDER_BACK.getValue().equals(value.getNoteType())) {
                if (value.getCount() >= 0) {
                    change.setOptType("110");
                } else {
                    change.setOptType("200");
                }
            } else if (StaticDict.STOCK_ADJUST_TYPE.ORDER_INPUT.getValue().equals(value.getNoteType())) {
                change.setOptType("100");
            } else if (StaticDict.STOCK_ADJUST_TYPE.ADJUST.getValue().equals(value.getNoteType())) {
                if (value.getCount() >= 0) {
                    change.setOptType("120");
                } else {
                    change.setOptType("150");
                }
            } else {
                if (value.getCount() >= 0) {
                    change.setOptType("190");
                } else {
                    change.setOptType("200");
                }
            }
            change.setRefNo(value.getThirdOrderNumber());
            change.setStartQty(value.getAfterCount() - value.getCount());
            change.setEndQty(value.getAfterCount());
            change.setChangeQty(value.getCount());
            change.setChangeTime(value.getCreateTime().getTime());
            change.setRemark(StaticDict.STOCK_ADJUST_TYPE.getText(value.getNoteType()));
            inventoryChangeList.add(change);
        }
        response.setSuccess(true);
        response.setResult(new InventoryChangeListResponse.Result(listPage.getPageInfo().getTotal(), inventoryChangeList));
        return response;
    }


    /**
     * 对接仓商品库存发生变化后，推送库存流水的变动给 TEMU
     * 对接仓通过(bg.certified.warehouse.inventory.change.push)推送库存变动流水信息
     */
    @Override

    public SingleResult inventoryChangePush(InventoryChangePushReq req, Long companyId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>()
                .eq(CompanyAuthorizeDo::getCompanyCode, req.getCwCustomCode())
                .orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null || et.getActive() == 0) {
            return SingleResult.failure(SysConstant.TemuAuth_Not_EXIST_Error);
//            throw new BizException(SysConstant.TemuAuth_Not_EXIST_Error);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("cwProviderCode", "JDY");
        paramMap.put("cwProviderName", "筋斗云");
        paramMap.put("cwSkuCode", req.getCwSkuCode());
        paramMap.put("cwCustomCode", et.getCompanyCode());

        paramMap.put("cwWarehouseCode", req.getCwWarehouseCode());
        paramMap.put("platformOpt", req.isPlatformOpt());
        paramMap.put("uniqueId", req.getUniqueId());
        paramMap.put("optType", req.getOptType());
        paramMap.put("refNo", req.getRefNo());
        paramMap.put("startQty", req.getStartQty());
        paramMap.put("endQty", req.getEndQty());
        paramMap.put("changeQty", req.getChangeQty());
        paramMap.put("changeTime", req.getChangeTime());
        paramMap.put("remark", req.getRemark());

        String result = null;
        try {
            result = TemuUtils.doPost("bg.certified.warehouse.inventory.change.push", et.getToken(), paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(result)) {
            return SingleResult.failure("500", "连接超时");
        }
        InventoryChangePushResponse res = JSON.parseObject(result, InventoryChangePushResponse.class);
        if (res.getSuccess() != null && res.getSuccess()) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(res.getErrorCode() + ": " + res.getErrorMsg());
        }
    }


    /**
     * 合作仓履约订单下发
     * temu 合作仓后台统一的订单分发接口，通过(bg.certified.warehouse.order.create)给合作仓下单
     *
     * @param req
     * @return
     */
    @Override
    public WarehouseOrderCreateResponse temuOrderCreate(WarehouseOrderCreateReq req) {
        WarehouseOrderCreateResponse response = new WarehouseOrderCreateResponse();
        log.debug("temuOrderCreate", JSONObject.toJSONString(req));
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            response.setErrorCode(checkRes.getErrorCode());
            response.setErrorMsg(checkRes.getErrorMsg());
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "99"));
            return response;
        }
        Map<String, Long> skuIdMap = new HashMap<>();
        for (WarehouseOrderCreateReq.Order order : req.getOrderList()) {
            if (skuIdMap.get(order.getCwSkuCode()) != null) {
                continue;
            }
            Long productId = productInfoService.getProductId(order.getCwSkuCode(), checkRes.getEt().getCompanyId());
            if (productId == null) {
                response.setErrorCode(120000);
                response.setErrorMsg("商品sku" + order.getCwSkuCode() + " 未匹配");
                response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "99"));
                return response;
            }
            skuIdMap.putIfAbsent(order.getCwSkuCode(), productId);
        }


        Long storageId = null;
        if (StringUtils.isNotBlank(req.getCwWarehouseCode())) {
            StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, req.getCwWarehouseCode()).last(" order by id desc limit 1"));
            if (storageDo == null) {
                response.setErrorCode(500000);
                response.setErrorMsg("对接仓仓库编码 未匹配");
                response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "99"));
                return response;
            }
            storageId = storageDo.getId();
        }
        if (storageId == null) {
            storageId = 13L;
        }
        SkuAndShopRes shopResult = this.getShopId(req.getOrderList(), storageId, checkRes.getEt().getShopId(), checkRes.getEt().getCompanyId());
        List<Long> shopList = shopResult.getShopList();
        if (shopList.isEmpty()) {
            response.setErrorCode(110000);
            response.setErrorMsg(shopResult.getSku() + "库存不足");
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "99"));
            return response;
        }
        //封装 req
        TemuProductRes temuProductRes = this.getOutAddReq(req, skuIdMap, storageId, shopList.get(0), checkRes.getEt().getCompanyId());
        OpenApiOrderOutputAddReq outReq = temuProductRes.getOutReq();
        String result = orderOutputService.openApiAddCatchExcption(outReq, checkRes.getEt().getCompanyId(), 1L);
        if (StringUtils.isNotBlank(result)) {
            response.setErrorCode(666666);
            response.setErrorMsg(result);
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "99"));
            return response;
        }

        response.setSuccess(true);
        //接单成功
        response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "10"));
        //保存temu商品详情
        orderOutputTemuProductService.saveBatch(temuProductRes.getTemuProductDos());
        return response;
    }


    /**
     * 合作仓履约平台面单订单下发
     * temu 合作仓后台统一的订单分发接口，通过(bg.certified.warehouse.order.createWithLabel)给合作仓下单
     *
     * @param req
     * @return
     */
    @Override
    public WarehouseOrderCreateResponse temuOrderCreateWithLabel(OrderCreateWithLabelReq req) {
        WarehouseOrderCreateResponse response = new WarehouseOrderCreateResponse();

        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            response.setErrorCode(checkRes.getErrorCode());
            response.setErrorMsg(checkRes.getErrorMsg());
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
            return response;
        }
        Map<String, Long> skuIdMap = new HashMap<>();
        for (WarehouseOrderCreateReq.Order order : req.getOrderList()) {
            if (skuIdMap.get(order.getCwSkuCode()) != null) {
                continue;
            }
            Long productId = productInfoService.getProductId(order.getCwSkuCode(), checkRes.getEt().getCompanyId());
            if (productId == null) {
                response.setErrorCode(120000);
                response.setErrorMsg("商品sku" + order.getCwSkuCode() + " 未匹配");
                response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
                return response;
            }
            skuIdMap.putIfAbsent(order.getCwSkuCode(), productId);
        }


        Long storageId = null;
        if (StringUtils.isNotBlank(req.getCwWarehouseCode())) {
            StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, req.getCwWarehouseCode()).last(" order by id desc limit 1"));
            if (storageDo == null) {
                response.setErrorCode(500000);
                response.setErrorMsg("对接仓仓库编码 未匹配");
                response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
                return response;
            }
            storageId = storageDo.getId();
        }
        if (storageId == null) {
            storageId = 13L;
        }
        SkuAndShopRes shopResult = this.getShopId(req.getOrderList(), storageId, checkRes.getEt().getShopId(), checkRes.getEt().getCompanyId());
        List<Long> shopList = shopResult.getShopList();
        if (shopList.isEmpty()) {
            response.setErrorCode(110000);
            response.setErrorMsg(shopResult.getSku() + "库存不足");
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
            return response;
        }
        //封装 req
        TemuProductRes temuProductRes = this.getOutAddReq(req, skuIdMap, storageId, shopList.get(0), checkRes.getEt().getCompanyId());
        OpenApiOrderOutputAddReq outReq = temuProductRes.getOutReq();
        //保存面单
        InputStream stream = null;
        try {
            stream = Base64AndFileStreamUtil.base64ToFile(req.getShippingLabel());
        } catch (IOException e) {
            response.setErrorCode(180000);
            response.setErrorMsg("面单保存出错，请重试");
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
            return response;
        }
        Long fileId = fileService.uploadFileToFormalPath(stream, req.getBatchOrderNo() + "面单." + req.getImgType());
        if (fileId == 0) {
            response.setErrorCode(180000);
            response.setErrorMsg("面单保存出错，请重试");
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
            return response;
        }
        outReq.setLabelFileId(fileId);
        //todo 匹配物流商品牌
        outReq.setTrackId(8L);
        outReq.setTrackNumber(req.getTrackingNumber());

        String result = orderOutputService.openApiAddCatchExcption(outReq, checkRes.getEt().getCompanyId(), 1L);
        if (StringUtils.isNotBlank(result)) {
            response.setErrorCode(666666);
            response.setErrorMsg(result);
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), null));
            return response;
        }

        response.setSuccess(true);
        //接单成功
        response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "20"));
        //保存temu商品详情
        orderOutputTemuProductService.saveBatch(temuProductRes.getTemuProductDos());
        return response;
    }

    /**
     * 商家需要取消履约订单
     * temu 要取消订单，通过(bg.certified.warehouse.order.cancel)给合作仓系统取消订单
     *
     * @param req
     * @return
     */
    @Override
    public TemuOrderCancelResponse temuOrderCancel(TemuOrderCancelReq req) {
        log.debug("temuOrderCancelReq", JSONObject.toJSONString(req));
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        TemuOrderCancelResponse response = new TemuOrderCancelResponse();
        if (!checkRes.getSuccess()) {
            response.setErrorCode(checkRes.getErrorCode());
            response.setErrorMsg(checkRes.getErrorMsg());
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "70"));
            return response;
        }
        OrderOutputDo order = orderOutputService.getOne(new LambdaQueryWrapper<OrderOutputDo>()
                .eq(OrderOutputDo::getCompanyId, checkRes.getEt().getCompanyId())
                .eq(OrderOutputDo::getPlatform, "temu")
                .eq(OrderOutputDo::getPlatformNumber, req.getBatchOrderNo()).last(" order by id desc limit 1"));
        if (order == null) {
            response.setErrorCode(130000);
            response.setErrorMsg("订单 " + req.getBatchOrderNo() + "不存在");
            response.setSuccess(false);
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "70"));
            return response;
        }

        if (DicBusinessItemConstant.outHasRecovered.equals(order.getStatus())) {
            response.setErrorCode(140000);
            response.setErrorMsg("订单 " + req.getBatchOrderNo() + "已取消");
            response.setSuccess(true);
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "60"));
            return response;
        }

        if (!DicBusinessItemConstant.outCreateCheckState.equals(order.getStatus()) && !DicBusinessItemConstant.outCreateState.equals(order.getStatus())) {
            response.setErrorCode(150000);
            response.setErrorMsg("订单 " + req.getBatchOrderNo() + "已在库内操作,无法取消");
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "70"));
            return response;
        }
        String result = orderOutputService.cutOffCatchException(order.getId(), 1L, checkRes.getEt().getCompanyId());
        if (StringUtils.isNotBlank(result)) {
            response.setErrorCode(150000);
            response.setErrorMsg(result);
            response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "70"));
            return response;
        }
        log.debug("temuOrderCancelRes", JSONObject.toJSONString(response));
        response.setSuccess(true);
        //取消接单成功
        response.setResult(new WarehouseOrderCreateResponse.Result(req.getBatchOrderNo(), "60"));
        return response;
    }

    @Override
    public WarehouseInfoListResponse temuWarehouseListGet(WarehouseInfoListReq req) {
        // TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        // if (!checkRes.getSuccess()) {
        //     return WarehouseInfoListResponse.builder().success(false).errorCode(checkRes.getErrorCode()).errorMsg(checkRes.getErrorMsg()).build();
        // }

        List<StorageDo> storageDoList = storageDao.selectList(
                Wrappers.<StorageDo>lambdaQuery()
                        .eq(StorageDo::getSupportShip, 1)
                        .eq(StorageDo::getDeleteFlag, 0)
        );
        List<CwWarehouseInfo> cwWarehouseInfoList = new ArrayList<>();
        for (StorageDo storageDo : storageDoList) {
            cwWarehouseInfoList.add(
                    CwWarehouseInfo.builder()
                            .cwWarehouseCode(storageDo.getCode())
                            .cwWarehouseName(storageDo.getCode() + " Warehouse")
                            .cwWarehouseRegionCode(storageDo.getCountryType() == 1 ? "JP" : "CN")
                            .build()
            );
        }
        return WarehouseInfoListResponse.builder()
                .success(true)
                .errorCode(0)
                .result(
                        WarehouseInfoListResponse.Result.builder()
                                .cwWarehouseInfoList(cwWarehouseInfoList)
                                .build()
                )
                .build();
    }


    public TemuProductRes getOutAddReq(WarehouseOrderCreateReq req, Map<String, Long> skuIdMap, Long
            storageId, Long shopId, Long companyId) {
        //封装 req
        OpenApiOrderOutputAddReq outReq = new OpenApiOrderOutputAddReq();
        outReq.setPlatform("temu");
        outReq.setPlatformNumber(req.getBatchOrderNo());
        outReq.setStorageId(storageId);
        outReq.setShopId(shopId);
        // outReq.setTips(req.getMallId());
        outReq.setOrderNo(req.getBatchOrderNo());
        outReq.setReceiverName(req.getConsignee().getReceiptName());
        outReq.setArea(req.getConsignee().getStateName());
        outReq.setAddress(req.getConsignee().getCityName() +
                (StringUtils.isNotBlank(req.getConsignee().getDistrict()) ? req.getConsignee().getDistrict() : "") +
                req.getConsignee().getAddressLine1() +
                (StringUtils.isNotBlank(req.getConsignee().getAddressLine2()) ? req.getConsignee().getAddressLine2() : "") +
                (StringUtils.isNotBlank(req.getConsignee().getHouseNo()) ? req.getConsignee().getHouseNo() : ""));
        outReq.setPostCode(req.getConsignee().getPostCode());
        outReq.setTelPhone(req.getConsignee().getMobile());

        // if (req.getEstimatedShippingTime() != null) {
        //     //预计发货时间
        //     long time = req.getEstimatedShippingTime() * 1000L;
        //     outReq.setSendDate(new Date(time));
        // }
        // if (req.getEstimatedDeliveryTime() != null) {
        //     //预计送达时间
        //     long time = req.getEstimatedDeliveryTime() * 1000L;
        //     outReq.setDeliveryDate(DateUtils.dateFormatToString(new Date(time)));
        // }
        List<OpenApiOrderOutputProductAddReq> productAddReqList = new ArrayList<>();
        List<OrderOutputTemuProductDo> temuProductDos = new ArrayList<>();
        //商品信息
        String parentNo = "";
        for (WarehouseOrderCreateReq.Order order : req.getOrderList()) {
            Long productId = skuIdMap.get(order.getCwSkuCode());
            //匹配SKU
            productAddReqList.add(new OpenApiOrderOutputProductAddReq(Integer.parseInt(order.getQty()), order.getCwSkuCode(), productId));
            temuProductDos.add(new OrderOutputTemuProductDo(req.getBatchOrderNo(), order.getParentOrderSn(), order.getOrderSn(), order.getCwSkuCode(), productId, Integer.parseInt(order.getQty())));
            parentNo = order.getParentOrderSn();
        }
        if (StringUtils.isNotBlank(parentNo)) {
            outReq.setOrderNo(parentNo);
        }
        outReq.setProductList(productAddReqList);
        return new TemuProductRes(temuProductDos, outReq);
    }

    public SkuAndShopRes getShopId(List<WarehouseOrderCreateReq.Order> orderList, Long storageId, Long shopId, Long companyId) {
        List<String> skuList = orderList.stream().map(WarehouseOrderCreateReq.Order::getCwSkuCode).distinct().collect(Collectors.toList());
        Map<String, Integer> temuSkuCountMap = orderList.stream().collect(Collectors.groupingBy(WarehouseOrderCreateReq.Order::getCwSkuCode, Collectors.summingInt(i -> Integer.parseInt(i.getQty()))));
        //先判断哪个店铺够
        Map<String, String> map = new HashMap<>();
        map.put("storageId", storageId + "");
        if (shopId != null)
            map.put("shopId", shopId + "");
        map.put("companyId", companyId + "");
        map.put("cwSkuCodeList", StringUtils.join(skuList, ","));
        //获取库存 多店铺
        List<StockRecordPageDto> stockList = stockRecordDao.listPage(map);
        Map<String, List<StockRecordPageDto>> collect = stockList.stream().collect(Collectors.groupingBy(StockRecordPageDto::getCommoditySku));
        List<Long> shopList = stockList.stream().map(StockRecordPageDto::getShopId).distinct().collect(Collectors.toList());

        String skuCode = "";
        sku:
        for (String sku : collect.keySet()) {
            //判断店铺够不够
            int count = temuSkuCountMap.getOrDefault(sku, 0);
            if (count == 0) {
                continue;
            }
            for (StockRecordPageDto stockRecordPageDto : collect.get(sku)) {
                int canUseCount = stockRecordPageDto.getCanSellCount() - stockRecordPageDto.getNoDelivered() - stockRecordPageDto.getTurnFba();
                if (canUseCount < count) {
                    shopList.remove(stockRecordPageDto.getShopId());
                    if (shopList.isEmpty()) {
                        skuCode = sku;
                        break sku;
                    }
                }
            }
        }
        return new SkuAndShopRes(skuCode, shopList);
    }


    /**
     * 半托管对接仓批量查询某个仓库支持的或可达物流产品
     * temu 查询对接仓某个仓库支持物流产品列表
     *
     * @param req
     * @return
     */
    @Override
    public LogisticsProductListResponse logisticsProductListBatchGet(LogisticsProductListGet req) {
        // TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        // if (!checkRes.getSuccess()) {
        //     return new LogisticsProductListResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        // }

        LogisticsProductListResponse response = new LogisticsProductListResponse();

        List<LogisticsProductListResponse.LogisticsProductInfo> logisticsInfoList = new ArrayList<>();
        //获取快递方式
        for (StaticDict.Temu_Track_Type value : StaticDict.Temu_Track_Type.values()) {
            // if (StaticDict.Track_Type.isUseFlag(value.getValue()) == null || !StaticDict.Track_Type.isUseFlag(value.getValue())) {
            //     continue;
            // }
            logisticsInfoList.add(new LogisticsProductListResponse.LogisticsProductInfo(value.getText(), StaticDict.Track_Type.getText(value.getValue())));
        }

        Map<String, List<LogisticsProductListResponse.LogisticsProductInfo>> logisticsProductMap = new HashMap<>();
        logisticsProductMap.put(req.getCwWarehouseCode(), logisticsInfoList);
        response.setSuccess(true);
        response.setResult(new LogisticsProductListResponse.Result(logisticsProductMap));
        return response;
    }


    /**
     * 半托管合作对接仓预估派送费用接口
     * temu 下单前需要对某个仓库不同的物流产品进行费用预估，然后选择某个合适的物流产品下单
     *
     * @param req
     * @return
     */
    @Override
    public DeliveryFeeCalcResponse deliveryFeeCalc(DeliveryFeeCalcReq req) {
        log.debug("deliveryFeeCalcReq", JSONObject.toJSONString(req));
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new DeliveryFeeCalcResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
//        StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, req.getCwWarehouseCode()).last(" order by id desc limit 1"));
//        if (storageDo == null) {
//            return new DeliveryFeeCalcResponse(500000, "对接仓仓库编码 未匹配");
//        }
        DeliveryFeeCalcPushReq pushReq = new DeliveryFeeCalcPushReq(req.getBatchGroupId());
        pushReq.setCwProviderName(req.getCwProviderName());
        pushReq.setCwProviderCode(req.getCwProviderCode());
        List<DeliveryFeeCalcPushReq.DeliveryFee> deliveryFeeList = new ArrayList<>();
        batchOrderInfo:
        for (DeliveryFeeCalcReq.BatchOrderInfo batchOrderInfo : req.getBatchOrderInfoList()) {
            DeliveryFeeCalcPushReq.DeliveryFee deliveryFee = new DeliveryFeeCalcPushReq.DeliveryFee(batchOrderInfo.getBatchId(), batchOrderInfo.getCwWarehouseCode());
            Long trackId = null;
            if (StringUtils.isNotBlank(batchOrderInfo.getLogisticsProductCode())) {
                trackId = StaticDict.Temu_Track_Type.getValue(batchOrderInfo.getLogisticsProductCode());
                if (trackId == null) {
                    deliveryFee.setLogisticsProductCode(batchOrderInfo.getLogisticsProductCode());
                    deliveryFee.setCanDelivery(false);
                    deliveryFee.setCanNotDeliveryReason("物流产品代码未匹配");
                    deliveryFeeList.add(deliveryFee);
                    continue;
                }

            }
            StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, batchOrderInfo.getCwWarehouseCode()).last(" order by id desc limit 1"));
            List<OrderOutputProductDo> productDoList = new ArrayList<>();
            for (DeliveryFeeCalcReq.Order productMsgReq : batchOrderInfo.getOrderList()) {
                OrderOutputProductDo productDo = new OrderOutputProductDo();
                Long productId = productInfoService.getProductId(productMsgReq.getCwSkuCode(), checkRes.getEt().getCompanyId());
                if (productId == null) {
                    if (trackId == null) {
                        deliveryFee.setLogisticsProductCode(StaticDict.Track_Type.YamatoExpress.getValue() + "");
                    } else {
                        deliveryFee.setLogisticsProductCode(batchOrderInfo.getLogisticsProductCode());
                    }
                    deliveryFee.setCanDelivery(false);
                    deliveryFee.setCanNotDeliveryReason("商品sku" + productMsgReq.getCwSkuCode() + " 未匹配");
                    deliveryFeeList.add(deliveryFee);
                    continue batchOrderInfo;
//                    return new DeliveryFeeCalcResponse(120000, "商品sku" + productMsgReq.getCwSkuCode() + " 未匹配");
                }
                productDo.setProductId(productId);
                productDo.setCount(productMsgReq.getQty());
                productDoList.add(productDo);
            }
            List<Long> productIds = productDoList.stream().map(OrderOutputProductDo::getProductId).distinct().collect(Collectors.toList());
            Map<Long, ProductInfoDo> productmMap = new HashMap<>();
            if (!productIds.isEmpty()) {
                List<ProductInfoDo> productBeans = productInfoService.list(new LambdaQueryWrapper<ProductInfoDo>()
                        .in(ProductInfoDo::getId, productIds));
                productmMap = productBeans.stream().collect(Collectors.toMap(ProductInfoDo::getId, i -> i, (v1, v2) -> v1));
            }
            double[] maxPackageSize = orderOutputService.getMaxPackageSize(storageDo.getId(), productDoList, true, trackId, checkRes.getEt().getCompanyId(), productmMap, storageDo);
            //看成本哪个最便宜
            ShipPriceDo shipPriceDo = shipPriceService.queryByRegionAndSize(req.getPostCode(), maxPackageSize, null, null, storageDo.getId(), trackId, 1, null, checkRes.getEt().getCompanyId());
            if (shipPriceDo == null) {
                if (trackId != null&&StaticDict.Track_Type.YamatoExpress.getValue().equals(trackId)) {
                    shipPriceDo = shipPriceService.queryByRegionAndSize(req.getPostCode(), maxPackageSize, null, null, storageDo.getId(), StaticDict.Track_Type.YamatoExpressBig.getValue(), 1, null, checkRes.getEt().getCompanyId());
                    if (shipPriceDo != null) {
                        deliveryFee.setLogisticsProductCode(StaticDict.Temu_Track_Type.getText(StaticDict.Track_Type.YamatoExpress.getValue()));
                        CompanyDo companyDo = companyDao.selectById(checkRes.getEt().getCompanyId());
                        //获取报价
                        ShipPriceDo price = shipPriceService.queryByRegionAndSize(req.getPostCode(), maxPackageSize, null, null, storageDo.getId(), StaticDict.Track_Type.YamatoExpressBig.getValue(), companyDo.getShipPriceVersion(), null, checkRes.getEt().getCompanyId());
                        deliveryFee.setTotalFee(price == null ? "" : price.getPrice() + "");
                        deliveryFee.setCurrency("JPY");
                        deliveryFeeList.add(deliveryFee);
                        continue;
                    }
                }else if (trackId != null){
                    deliveryFee.setLogisticsProductCode(StaticDict.Temu_Track_Type.getText(StaticDict.Track_Type.YamatoExpress.getValue()));
                } else {
                    deliveryFee.setLogisticsProductCode(batchOrderInfo.getLogisticsProductCode());
                }
                deliveryFee.setCanDelivery(false);
                deliveryFee.setCanNotDeliveryReason("产品尺寸不符合");
                deliveryFeeList.add(deliveryFee);
            } else {
                DimensDo dimensDo = dimensDao.selectById(shipPriceDo.getDimensId());
                deliveryFee.setLogisticsProductCode(StaticDict.Temu_Track_Type.getText(dimensDo.getTrackId()));
                CompanyDo companyDo = companyDao.selectById(checkRes.getEt().getCompanyId());
                //获取报价
                ShipPriceDo price = shipPriceService.queryByRegionAndSize(req.getPostCode(), maxPackageSize, null, null, storageDo.getId(), trackId, companyDo.getShipPriceVersion(), null, checkRes.getEt().getCompanyId());
                deliveryFee.setTotalFee(price == null ? "" : price.getPrice() + "");
                deliveryFee.setCurrency("JPY");
                deliveryFeeList.add(deliveryFee);
            }

        }
        pushReq.setDeliveryFeeList(deliveryFeeList);
        //推送回temu
        threadPoolTaskExecutor.execute(() -> {
            this.deliveryFeeCalcPush(pushReq, checkRes.getEt().getCompanyId());
        });
        DeliveryFeeCalcResponse response = new DeliveryFeeCalcResponse();
        response.setSuccess(true);
        return response;
    }

    @Override
    public TemuBaseQueryRes<WarehouseOrderFeeQueryResponse> temuOrderFeeQuery(WarehouseOrderQueryReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new TemuBaseQueryRes(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }

        OrderOutputDo temuOrderOut = orderOutputService.getOne(new LambdaQueryWrapper<OrderOutputDo>().eq(OrderOutputDo::getPlatform, "temu")
                .eq(OrderOutputDo::getCompanyId, checkRes.getEt().getCompanyId())
                .eq(OrderOutputDo::getPlatformNumber, req.getBatchOrderNo()));
        if (temuOrderOut == null) {
            return new TemuBaseQueryRes(0, "Order does not exist");
        }
        TemuBaseQueryRes<WarehouseOrderFeeQueryResponse> result = new TemuBaseQueryRes<>();
        result.setSuccess(true);
        // List<OrderOutputTemuProductDo> temuProductDoList = orderOutputTemuProductDao.selectList(new LambdaQueryWrapper<OrderOutputTemuProductDo>()
        //         .eq(OrderOutputTemuProductDo::getOrderNo, temuOrderOut.getPlatformNumber()));
        // Map<Long, List<OrderOutputTemuProductDo>> temuProductMap = temuProductDoList.stream().collect(Collectors.groupingBy(OrderOutputTemuProductDo::getProductId));
        List<OrderOutputPackageDetailDo> orderOutputPackageDetailDos = packageDetailService.getBaseMapper().selectList(new LambdaQueryWrapper<OrderOutputPackageDetailDo>()
                .eq(OrderOutputPackageDetailDo::getOrderOutputId, temuOrderOut.getId()));
        Map<String, List<OrderOutputPackageDetailDo>> stringListMap = orderOutputPackageDetailDos.stream().distinct().collect(Collectors.groupingBy(OrderOutputPackageDetailDo::getTrackNumber));
        if (!orderOutputPackageDetailDos.isEmpty()) {
            int trackNumberCount = stringListMap.size();
            for (String trackNumber : stringListMap.keySet()) {
                if (trackNumber.contains(req.getTrackingNumber())) {
                    OrderOutputPackageDetailDo packageDetailDo = stringListMap.get(trackNumber).get(0);
                    WarehouseOrderFeeQueryResponse feeQueryResponse = new WarehouseOrderFeeQueryResponse();
                    feeQueryResponse.setChargeWeight(BigDecimal.valueOf(packageDetailDo.getWeight() * 1000 * 1000).longValue());
                    feeQueryResponse.setWeight(BigDecimal.valueOf(packageDetailDo.getWeight() * 1000 * 1000).longValue());
                    feeQueryResponse.setLength(BigDecimal.valueOf(((packageDetailDo.getMLength() == null || packageDetailDo.getMLength() == 0) ? packageDetailDo.getLength() : packageDetailDo.getMLength()) * 10).longValue());
                    feeQueryResponse.setWidth(BigDecimal.valueOf(((packageDetailDo.getMWidth() == null || packageDetailDo.getMWidth() == 0) ? packageDetailDo.getWidth() : packageDetailDo.getMWidth()) * 10).longValue());
                    feeQueryResponse.setHeight(BigDecimal.valueOf(((packageDetailDo.getMHeight() == null || packageDetailDo.getMHeight() == 0) ? packageDetailDo.getHeight() : packageDetailDo.getMHeight()) * 10).longValue());
                    feeQueryResponse.setCurrency("JPY");
                    String tailOtherFee = BigDecimal.valueOf(( temuOrderOut.getDiffPrice() + temuOrderOut.getTaxFee()) / trackNumberCount).setScale(2, RoundingMode.HALF_UP).toString();
                    feeQueryResponse.setTailOtherFee(tailOtherFee);
                    String innerWarehouseFee = BigDecimal.valueOf((temuOrderOut.getOperateFee() + temuOrderOut.getOutFee() +temuOrderOut.getCutFee()) / trackNumberCount).setScale(2, RoundingMode.HALF_UP).toString();
                    feeQueryResponse.setInnerWarehouseFee(innerWarehouseFee);
                    String tailDeliveryFee = BigDecimal.valueOf(temuOrderOut.getShipFee() / trackNumberCount).setScale(2, RoundingMode.HALF_UP).toString();
                    feeQueryResponse.setTailDeliveryFee(tailDeliveryFee);
                    String totalFee = BigDecimal.valueOf(Double.parseDouble(tailOtherFee) + Double.parseDouble(innerWarehouseFee) +
                            Double.parseDouble(tailDeliveryFee)).setScale(2, RoundingMode.HALF_UP).toString();
                    feeQueryResponse.setTotalFee(totalFee);

                    List<WarehouseOrderFeeQueryResponse.FeeListDTO> feeListDTOList = new ArrayList<>();
                    feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(BigDecimal.valueOf(temuOrderOut.getOperateFee() / trackNumberCount).toString(), "", "库内操作费", 0, 1));
                    if (temuOrderOut.getCutFee() != 0)
                        feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(BigDecimal.valueOf(temuOrderOut.getCutFee() / trackNumberCount).toString(), "", "截单操作费", 0, 1));
                    if (temuOrderOut.getDiffPrice() != 0)
                        feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(BigDecimal.valueOf(temuOrderOut.getDiffPrice() / trackNumberCount).toString(), "", "切换渠道追加费", 7, 4));

                    feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(tailDeliveryFee, "", "快递运输费", 0, 2));
                    if (temuOrderOut.getTaxFee() != 0)
                        feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(BigDecimal.valueOf(temuOrderOut.getTaxFee() / trackNumberCount).toString(), "", "税费", 7, 4));
                    if (temuOrderOut.getOutFee() != 0)
                        feeListDTOList.add(new WarehouseOrderFeeQueryResponse.FeeListDTO(BigDecimal.valueOf(temuOrderOut.getOutFee() / trackNumberCount).toString(), "", "包装耗材费", 7, 1));
                    feeQueryResponse.setFeeList(feeListDTOList);
                    result.setResult(feeQueryResponse);
                    break;
                }
            }
        }
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public TemuReturnOrderOperateResponse temuReturnOrderCreate(TemuReturnOrderCreateReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(
                new TemuAuthTokenVerifyReq(
                        req.getCwCustomCode(),
                        req.getCwAppKey(),
                        req.getCwAccessToken()
                )
        );
        //认证失败
        if (!checkRes.getSuccess()) {
            return TemuReturnOrderOperateResponse.builder()
                    .errorCode(checkRes.getErrorCode())
                    .errorMsg(checkRes.getErrorMsg())
                    .result(
                            TemuReturnOrderOperateResponse.Result.builder()
                                    .returnOrderNo(req.getReturnOrderNo())
                                    .orderStatus(ReturnOrderStatusEnum.Exception.getCode())
                                    .build()
                    ).build();
        }
        TemuOrderBackDo exisit = temuOrderBackService.getOne(
                Wrappers.<TemuOrderBackDo>lambdaQuery()
                        .eq(TemuOrderBackDo::getReturnOrderNo, req.getReturnOrderNo())
                        .last(" limit 1")
        );
        if (Objects.nonNull(exisit)) {
            //已经存在该退货单，判断状态返回
//            Integer status = exisit.getStatus();
            return TemuReturnOrderOperateResponse.builder()
                    .result(
                            TemuReturnOrderOperateResponse.Result.builder()
                                    .returnOrderNo(req.getReturnOrderNo())
//                                    .orderStatus(ReturnOrderStatusEnum.getCodeByLocationStatus(status))
                                    .orderStatus(ReturnOrderStatusEnum.CREATED.getCode())
                                    .build()
                    ).build();
        }
        TemuOrderBackDo mainDo = new TemuOrderBackDo();
        mainDo.setReturnOrderNo(req.getReturnOrderNo());
        mainDo.setStatus(0);
        mainDo.setCwWarehouseCode(req.getCwWarehouseCode());
        mainDo.setLogisticsProviderName(req.getLogisticsProviderName());
        mainDo.setWaybillSn(req.getWaybillSn());
        mainDo.setAuxiliaryWaybillSnList(JSONArray.toJSONString(req.getAuxiliaryWaybillSnList()));
        mainDo.setName(req.getRecipientAddress().getName());
        mainDo.setEmail(req.getRecipientAddress().getEmail());
        mainDo.setPhone(req.getRecipientAddress().getPhone());
        mainDo.setCountryCode(req.getRecipientAddress().getRegionShort1());
        mainDo.setState(req.getRecipientAddress().getRegionName2());
        mainDo.setCity(req.getRecipientAddress().getRegionName3());
        mainDo.setArea(req.getRecipientAddress().getRegionName4());
        mainDo.setPostCode(req.getRecipientAddress().getPostcode());
        mainDo.setHouseNo(req.getRecipientAddress().getHouseNo());
        mainDo.setStreet(req.getRecipientAddress().getAddressLine1());
        mainDo.setApt(req.getRecipientAddress().getAddressLine2());
        mainDo.setLength(Math.toIntExact(req.getPackageInfo().getLength()));
        mainDo.setWidth(Math.toIntExact(req.getPackageInfo().getWidth()));
        mainDo.setHeight(Math.toIntExact(req.getPackageInfo().getHeight()));
        mainDo.setWeight(Math.toIntExact(req.getPackageInfo().getWeight()));
        temuOrderBackService.save(mainDo);
        List<TemuOrderBackProductDo> temuOrderBackProductList = new ArrayList<>();
        for (ReturnGoods returnGoods : req.getReturnGoodsList()) {
            TemuOrderBackProductDo productDo = new TemuOrderBackProductDo();
            productDo.setMainTableId(mainDo.getId());
            productDo.setReturnOrderNo(req.getReturnOrderNo());
            productDo.setBatchOrderNo(returnGoods.getBatchOrderNo());
            productDo.setProductSku(returnGoods.getProductCode());
            productDo.setProductNum(returnGoods.getProductNum());
            productDo.setHandleMethod(returnGoods.getHandleMethod().getValue());
            productDo.setShelveMethod(returnGoods.getShelveMethod().getValue());
            productDo.setGoodMethod(returnGoods.getGoodMethod().getValue());
            productDo.setDefectiveMethod(returnGoods.getDefectiveMethod().getValue());
            temuOrderBackProductList.add(productDo);
        }
        temuOrderBackProductService.saveBatch(temuOrderBackProductList);
        return TemuReturnOrderOperateResponse.builder()
                .result(
                        TemuReturnOrderOperateResponse.Result.builder()
                                .returnOrderNo(req.getReturnOrderNo())
                                .orderStatus(ReturnOrderStatusEnum.CREATED.getCode())
                                .build()
                ).build();
    }

    @Override
    public TemuReturnOrderOperateResponse temuReturnOrderUpdate(TemuReturnOrderUpdateReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(
                new TemuAuthTokenVerifyReq(
                        req.getCwCustomCode(),
                        req.getCwAppKey(),
                        req.getCwAccessToken()
                )
        );
        //认证失败
        if (!checkRes.getSuccess()) {
            return TemuReturnOrderOperateResponse.builder()
                    .errorCode(checkRes.getErrorCode())
                    .errorMsg(checkRes.getErrorMsg())
                    .result(
                            TemuReturnOrderOperateResponse.Result.builder()
                                    .returnOrderNo(req.getReturnOrderNo())
                                    .orderStatus(ReturnOrderStatusEnum.Exception.getCode())
                                    .build()
                    ).build();
        }
        try {
            for (ReturnGoods returnGoods : req.getReturnGoodsList()) {
                temuOrderBackProductService.lambdaUpdate()
                        .set(StringUtils.isNotBlank(returnGoods.getProductCode()), TemuOrderBackProductDo::getProductSku, returnGoods.getProductCode())
                        .set(Objects.nonNull(returnGoods.getProductNum()), TemuOrderBackProductDo::getProductNum, returnGoods.getProductNum())
                        .set(Objects.nonNull(returnGoods.getHandleMethod()), TemuOrderBackProductDo::getHandleMethod, returnGoods.getHandleMethod().getValue())
                        .set(Objects.nonNull(returnGoods.getShelveMethod()), TemuOrderBackProductDo::getShelveMethod, returnGoods.getShelveMethod().getValue())
                        .set(Objects.nonNull(returnGoods.getGoodMethod()), TemuOrderBackProductDo::getGoodMethod, returnGoods.getGoodMethod().getValue())
                        .set(Objects.nonNull(returnGoods.getDefectiveMethod()), TemuOrderBackProductDo::getDefectiveMethod, returnGoods.getDefectiveMethod().getValue())
                        .eq(TemuOrderBackProductDo::getReturnOrderNo, req.getReturnOrderNo())
                        .eq(TemuOrderBackProductDo::getBatchOrderNo, returnGoods.getBatchOrderNo())
                        .update();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("temu退货单更新异常", e);
            return TemuReturnOrderOperateResponse.builder()
                    .errorCode(100009)
                    .errorMsg("退货单更新异常")
                    .result(
                            TemuReturnOrderOperateResponse.Result.builder()
                                    .returnOrderNo(req.getReturnOrderNo())
                                    .orderStatus(ReturnOrderStatusEnum.UpdateFailure.getCode())
                                    .build()
                    ).build();
        }
        return TemuReturnOrderOperateResponse.builder()
                .result(
                        TemuReturnOrderOperateResponse.Result.builder()
                                .returnOrderNo(req.getReturnOrderNo())
                                .orderStatus(ReturnOrderStatusEnum.UpdateSuccess.getCode())
                                .build()
                ).build();
    }

    @Override
    public TemuReturnOrderOperateResponse temuReturnOrderCancel(TemuReturnOrderCancelReq req) {
        TemuAuthVerifyRes checkRes = this.tokenVerify(
                new TemuAuthTokenVerifyReq(
                        req.getCwCustomCode(),
                        req.getCwAppKey(),
                        req.getCwAccessToken()
                )
        );
        //认证失败
        if (!checkRes.getSuccess()) {
            return TemuReturnOrderOperateResponse.builder()
                    .errorCode(checkRes.getErrorCode())
                    .errorMsg(checkRes.getErrorMsg())
                    .result(
                            TemuReturnOrderOperateResponse.Result.builder()
                                    .returnOrderNo(req.getReturnOrderNo())
                                    .orderStatus(ReturnOrderStatusEnum.Exception.getCode())
                                    .build()
                    ).build();
        }
        //TODO 做一些取消操作
        //修改状态
        boolean update = temuOrderBackService.lambdaUpdate()
                .set(TemuOrderBackDo::getStatus, 4)
                .eq(TemuOrderBackDo::getReturnOrderNo, req.getReturnOrderNo())
                .update();
        Integer orderStatus;
        if (update) {
            orderStatus = ReturnOrderStatusEnum.CancelSuccessful.getCode();
        } else {
            orderStatus = ReturnOrderStatusEnum.CancelFailure.getCode();
        }
        return TemuReturnOrderOperateResponse.builder()
                .result(
                        TemuReturnOrderOperateResponse.Result.builder()
                                .returnOrderNo(req.getReturnOrderNo())
                                .orderStatus(orderStatus)
                                .build()
                ).build();
    }


    /**
     * 半托管合作对接仓预估派送费用接口
     * temu 下单前需要对某个仓库不同的物流产品进行费用预估，然后选择某个合适的物流产品下单
     *
     * @param req
     * @param companyId
     * @return
     */
    public SingleResult deliveryFeeCalcPush(DeliveryFeeCalcPushReq req, Long companyId) {
        CompanyAuthorizeDo et = dao.selectOne(new LambdaQueryWrapper<CompanyAuthorizeDo>().eq(CompanyAuthorizeDo::getCompanyId, companyId).orderByDesc(CompanyAuthorizeDo::getId).last(" limit 1"));
        if (et == null || et.getActive() == 0) {
            return SingleResult.failure(SysConstant.TemuAuth_Not_EXIST_Error);
//            throw new BizException(SysConstant.TemuAuth_Not_EXIST_Error);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("cwProviderCode", req.getCwProviderCode());
        paramMap.put("cwProviderName", req.getCwProviderName());
        paramMap.put("batchGroupId", req.getBatchGroupId());

        List<Map<String, Object>> deliverFeeList = new ArrayList<>();
        for (DeliveryFeeCalcPushReq.DeliveryFee deliveryFee : req.getDeliveryFeeList()) {
            Map<String, Object> deliverFeeMap = new HashMap<>();
            deliverFeeMap.put("batchId", deliveryFee.getBatchId());
            deliverFeeMap.put("cwWarehouseCode", deliveryFee.getCwWarehouseCode());
            deliverFeeMap.put("logisticsProductCode", deliveryFee.getLogisticsProductCode());
            deliverFeeMap.put("canDelivery", deliveryFee.isCanDelivery());
            if (StringUtils.isNotBlank(deliveryFee.getCanNotDeliveryReason())) {
                deliverFeeMap.put("canNotDeliveryReason", deliveryFee.getCanNotDeliveryReason());
            }
            if (deliveryFee.getLogisticsTime() != null) {
                deliverFeeMap.put("logisticsTime", deliveryFee.getLogisticsTime());
            }
            if (StringUtils.isNotBlank(deliveryFee.getCurrency())) {
                deliverFeeMap.put("currency", deliveryFee.getCurrency());
            }
            if (StringUtils.isNotBlank(deliveryFee.getTotalFee())) {
                deliverFeeMap.put("totalFee", deliveryFee.getTotalFee());
            }

            //费用列表
            if (deliveryFee.getFeeList() != null && !deliveryFee.getFeeList().isEmpty()) {
                List<Map<String, Object>> feeListMap = new ArrayList<>();
                for (DeliveryFeeCalcPushReq.FeeInfo feeInfo : deliveryFee.getFeeList()) {
                    Map<String, Object> feeMap = new HashMap<>();
                    feeMap.put("fee", feeInfo.getFee());
                    feeMap.put("currency", feeInfo.getCurrency());
                    feeMap.put("feeDesc", feeInfo.getFeeDesc());
                    feeMap.put("feeCode", feeInfo.getFeeCode());
                    feeListMap.add(feeMap);
                }

                deliverFeeMap.put("feeList", feeListMap);
            }
            deliverFeeList.add(deliverFeeMap);
        }
        paramMap.put("deliveryFeeList", deliverFeeList);
        log.debug("deliveryFeeCalcPOSTPara", JSONObject.toJSONString(paramMap));
        String result = null;
        try {
            result = TemuUtils.doPost("bg.certified.warehouse.delivery.fee.calc.push", et.getToken(), paramMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(result)) {
            return SingleResult.failure("500", "连接超时");
        }
        log.debug("deliveryFeeCalcPOSTResult", result);
        DeliveryFeeCalcPushResponse res = JSON.parseObject(result, DeliveryFeeCalcPushResponse.class);
        if (res.getSuccess() != null && res.getSuccess()) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(res.getErrorCode() + ": " + res.getErrorMsg());
        }
    }

    @Override
    public WarehouseOrderQueryResponse temuOrderQuery(WarehouseOrderQueryReq req) {
        WarehouseOrderQueryResponse response = new WarehouseOrderQueryResponse();
        TemuAuthVerifyRes checkRes = this.tokenVerify(new TemuAuthTokenVerifyReq(req.getCwCustomCode(), req.getCwAppKey(), req.getCwAccessToken()));
        if (!checkRes.getSuccess()) {
            return new WarehouseOrderQueryResponse(checkRes.getErrorCode(), checkRes.getErrorMsg());
        }
        OrderOutputDo temuOrderOut = orderOutputService.getOne(new LambdaQueryWrapper<OrderOutputDo>().eq(OrderOutputDo::getPlatform, "temu")
                .eq(OrderOutputDo::getCompanyId, checkRes.getEt().getCompanyId())
                .eq(OrderOutputDo::getPlatformNumber, req.getBatchOrderNo()));
        if (temuOrderOut == null) {
            return new WarehouseOrderQueryResponse(0, "Order does not exist");
        }
        response.setSuccess(true);

        int orderStatus = 10;
        String failReason = null;
        if (DicBusinessItemConstant.outSendOut <= temuOrderOut.getStatus() && DicBusinessItemConstant.outPushError >= temuOrderOut.getStatus()) {
            //发货完成
            orderStatus = 50;
        } else if (DicBusinessItemConstant.waitingPickUp.equals(temuOrderOut.getStatus())) {
            orderStatus = 10;
        } else if (DicBusinessItemConstant.alreadyPickUp.equals(temuOrderOut.getStatus())) {
            orderStatus = 10;
        } else if (DicBusinessItemConstant.outWaitCheckOut.equals(temuOrderOut.getStatus())) {
            orderStatus = 10;
        } else if (DicBusinessItemConstant.outHasRecovered.equals(temuOrderOut.getStatus())) {
            orderStatus = 10;
        } else if (DicBusinessItemConstant.orderCutOff.equals(temuOrderOut.getStatus())) {
            orderStatus = 10;
        } else if (DicBusinessItemConstant.problemShipment.equals(temuOrderOut.getStatus()) && StringUtils.isNotBlank(temuOrderOut.getProblemReason())) {
            orderStatus = 99;
            failReason = temuOrderOut.getProblemReason();
        } else {

        }
        DicBusinessItemDo itemDo = dicBusinessItemDao.selectById(temuOrderOut.getTrackId());
        if (itemDo == null) {
            itemDo = new DicBusinessItemDo();
            itemDo.setParentId(9L);
        }
        String code = storageDao.selectById(temuOrderOut.getStorageId()).getCode();
        WarehouseOrderQueryResponse.Result result = new WarehouseOrderQueryResponse.Result(temuOrderOut.getPlatformNumber(), String.valueOf(orderStatus),
                code, StaticDict.Temu_Track_Type.getText(itemDo.getId().equals(StaticDict.Temu_Track_Type.YamatoSExpress.getValue()) ? itemDo.getId() : itemDo.getParentId()));
        response.setResult(result);
        if (failReason != null) {
            result.setFailReason(failReason);
        }
        List<OrderOutputTemuProductDo> temuProductDoList = orderOutputTemuProductDao.selectList(new LambdaQueryWrapper<OrderOutputTemuProductDo>().eq(OrderOutputTemuProductDo::getOrderNo, temuOrderOut.getPlatformNumber()));
        Map<Long, List<OrderOutputTemuProductDo>> temuProductMap = temuProductDoList.stream().collect(Collectors.groupingBy(OrderOutputTemuProductDo::getProductId));
        List<OrderOutputPackageDetailDo> orderOutputPackageDetailDos = packageDetailService.getBaseMapper().selectList(new LambdaQueryWrapper<OrderOutputPackageDetailDo>().eq(OrderOutputPackageDetailDo::getOrderOutputId, temuOrderOut.getId()));
        if (orderStatus == 50 && !orderOutputPackageDetailDos.isEmpty()) {
            List<WarehouseOrderQueryResponse.Package> packageList = new ArrayList<>();
            for (OrderOutputPackageDetailDo orderOutputPackageDetailDo : orderOutputPackageDetailDos) {
                WarehouseOrderQueryResponse.Package aPackage = new WarehouseOrderQueryResponse.Package(StaticDict.Temu_Track_Type.getText(itemDo.getParentId()),
                        orderOutputPackageDetailDo.getTrackNumber(), Math.toIntExact(temuOrderOut.getSendTime().getTime() / 1000) + 3600);
                List<WarehouseOrderQueryResponse.Package.Order> orderList = new ArrayList<>();
                String[] split = orderOutputPackageDetailDo.getInSkuId().split(",");
                if (split.length < 1) {
                    continue;
                }
                Map<String, Long> stringLongMap = Arrays.stream(split).collect(Collectors.groupingBy(s -> s, Collectors.counting()));

                for (String productId : stringLongMap.keySet()) {
                    for (OrderOutputTemuProductDo temuProductDo : temuProductMap.get(Long.parseLong(productId))) {
                        orderList.add(new WarehouseOrderQueryResponse.Package.Order(temuProductDo.getOrderSn(),
                                temuProductDo.getCwSkuCode(), Math.toIntExact(stringLongMap.get(productId))));
                    }
                }
                aPackage.setOrderList(orderList);
                packageList.add(aPackage);
            }
            result.setPackageList(packageList);
        }
        return response;
    }
}
